import sched 
import rtmidi
import time 
import random
import notes


def note_on( ch , note , vel ):
    o.sendMessage( 0x90 | ch , note , vel )
    
def note_off( ch , note , vel ):
    o.sendMessage( 0x80 | ch , note , vel )
    
def constrain( n ):
    if n< 0:
        return 0
    if n > 127:
        return 127
    return n        
    
def pick( m , s ):
    return constrain( int(  random.gauss( m , s ) ))
    
def schedule_note( s , ch , t , n , v , l ):
    s.enter( t , 1 , note_on , [ ch , n , v] )
    s.enter( t + l , 1 , note_off , [ ch , n , v] )       
    
    
def make_some_notes( s , ch , n ):
    for i in range( n):
        t =  random.gauss( 10 , 5 )
        n = pick( 60 , 30 )
        v = pick( 100 , 10 )
        schedule_note( s , 0 , t , n , v , 0.5 )
                                    
        
def delay_func( n ):
    if  n == 0:
        if random.random() > 0.99:
            #make_some_notes( s , 0 , int( random.gauss( 50 , 20 ) ) )
            print 'making some notes'
    else:            
        time.sleep( n )        
        
        

o = rtmidi.RtMidiOut()
o.openPort( 0 )
s = sched.scheduler( time.time ,delay_func )        

t = 0
for i in range( 100 ):
    t +=  random.gauss( 0.5 , 0.015 )
    schedule_note(  s , 0 , t , notes.note_from_name( "F#3" ) , 110 , 0.5 )
    
t = 0
for i in range( 100 ):
    t +=  random.gauss( 0.7 , 0.015 )
    schedule_note(  s , 1 , t , notes.note_from_name( "A#3" )  , 110 , 0.5 )    
    
t = 0
for i in range( 100 ):
    t +=  random.gauss( 0.8 , 0.015 )
    schedule_note(  s , 1 , t , notes.note_from_name( "D#3" )  , 110 , 0.5 )        
   

#make_some_notes( s , 0 , 30 )
s.run()
    